package com.mg.filter;

import com.mg.common.Constants;
import com.mg.model.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author mg1213
 * 2018/3/22
 **/
@Component
@WebFilter(urlPatterns = "/", filterName = "authFilter")
public class AuthFilter implements Filter {
    @Value("${excludeUrl}")
    private String excludeUrls;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(Constants.USER_INFO);
        String url = request.getRequestURL().toString();
        if (user == null) {
            String[] excludeUrlArr = excludeUrls.split(",");
            boolean flag = false;
            for (String excludeUrl : excludeUrlArr) {
                if (url.contains(excludeUrl)) {
                    flag = true;
                    break;
                }
            }

            if (url.endsWith(".js")||url.endsWith(".jpg") || url.endsWith(".css") || url.endsWith(".gif") || url.endsWith(".png")|| url.endsWith(".ico")||url.endsWith(".map")
                    || url.endsWith(".svg") || url.endsWith(".woff")|| url.endsWith(".woff2")  || url.endsWith(".svg") || url.endsWith(".eot") || url.endsWith(".swf")) {
                flag = true;
            }
            if (!flag) {
                request.getRequestDispatcher("/pages/main/index.jsp").forward(request, response);
//                response.sendRedirect(request.getContextPath() + "/pages/main/index.jsp");
                return;
            }
        } else {
            if (url.contains("admin") && !Constants.ADMIN_NAME.equals(user.getUserName())) {
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
